/*
package cn.xinfei.xdecision.engine.runner.datax;

import cn.xinfei.xdecision.common.datamodel.DecisionDataQueryLog;
import cn.xinfei.xdecision.common.model.datax.enums.CreditInquiryStatus;
import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataExceptionType;
import cn.xinfei.xdecision.constant.EngineResultEnum;
import cn.xinfei.xdecision.data.RiskDataApiInterface;
import cn.xinfei.xdecision.engine.runner.context.PipelineContextHolder;
import cn.xinfei.xdecision.engine.runner.context.XDecisionContext;
import cn.xinfei.xdecision.engine.runner.executor.model.StateTransmitModel;
import cn.xinfei.xdecision.engine.runner.metadata.PrometheusTagsConstants;
import cn.xinfei.xdecision.engine.runner.service.DecisionDataQueryService;
import cn.xinfei.xdecision.engine.runner.service.DecisionResultService;
import cn.xinfei.xdecision.model.CreditVarRequest;
import cn.xinfei.xdecision.model.CreditVarResponse;
import cn.xinfei.xdecision.model.VariableApiRequest;
import cn.xinfei.xdecision.model.VariableApiResponse;
import cn.xinfei.xdecision.pulsar.XPulsarProducer;
import cn.xinfei.xdecision.pulsar.config.XDecisionMessage;
import com.alibaba.fastjson.JSONObject;
import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.MessageId;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentMap;

@Data
@Slf4j
@Service
public abstract class RiskDataApiAdapterbak {

    @Autowired
    private XPulsarProducer xPulsarProducer;

    @Value("${xdecision.decisionresult.dataxQueryLogTopic}")
    private String queryLogTopic;

    @Autowired
    private MeterRegistry meterRegistry;

    @Autowired
    private RiskDataApiInterface riskDataApiInterface;

    @Autowired
    private DecisionResultService decisionResultService;

    @Autowired
    private DecisionDataQueryService decisionDataQueryService;

    public enum CollectTypeEnum {
        PRE, REAL, CREDIT, CREDIT_DATA
    }


    public StateTransmitModel queryFieldValue(String nodeCode, Set<String> fields, CollectTypeEnum type) {
        StateTransmitModel engineResultEnum = XDecisionContext.getContext().getStateContext().setEngineResultEnum(EngineResultEnum.PROCESSING);
        if (PipelineContextHolder.isInvokeRemote() == false) {
            log.info("测试数据不发起远程调用");
            return engineResultEnum;
        }


        if (CollectionUtils.isEmpty(fields)) {
            log.info("不需要加载变量，fields is empty，type={}", type);
            meterRegistry.counter("xengine_xdata_" + type + "_null_total", PrometheusTagsConstants.XDATA_API_TOTAL_TAGS).increment();
            return engineResultEnum;
        }

        String response = "";
        long respond = 0;
        String code = "null";
        Transaction transaction = Cat.newTransaction("xengine", type.name());
        Long start = System.currentTimeMillis();
        VariableApiRequest variableApiRequest = new VariableApiRequest();
        try {

            String decisionId = PipelineContextHolder.getDecisionId();
            variableApiRequest.setVarCodes(fields);
            variableApiRequest.setRequestId(decisionId);
            variableApiRequest.setInputParams(JSONObject.parseObject(JsonUtil.toJson(PipelineContextHolder.getContextValue())));
            String bizId = PipelineContextHolder.getRequestId();

            VariableApiResponse dataApiResponse = null;
            if (CollectTypeEnum.PRE == type) {
                dataApiResponse = riskDataApiInterface.preCollect(variableApiRequest);
            } else if (CollectTypeEnum.REAL == type) {
                dataApiResponse = riskDataApiInterface.realCollect(variableApiRequest);
            } else if (CollectTypeEnum.CREDIT == type) {
                dataApiResponse = riskDataApiInterface.fetchCreditVars(variableApiRequest);
            }
            Long end = System.currentTimeMillis();

            respond = end - start;

            Metrics.gauge("xengine_xdata_respond", PrometheusTagsConstants.XDATA_API_RESPOND_TAGS.and(Tags.of("type", type.name())), respond);
            transaction.setDurationInMillis(respond);
            transaction.setStatus(Transaction.SUCCESS);

            log.info("变量中心采集数据请求报文，type={},respond={},response={},request={}", type, respond, JsonUtil.toJson(dataApiResponse), JsonUtil.toJson(variableApiRequest));
            if (null != dataApiResponse) {
                response = JsonUtil.toJson(dataApiResponse);
                code = dataApiResponse.getCode();
                if (String.valueOf(XDecisionDataExceptionType.SUCCESS.code).equals(code) || CreditInquiryStatus.QUERY_SUCCESS.getStatusName().equals(code)) {
                    String variablesResponse = dataApiResponse.getVariablesResponse();
                    Map fieldInfo = JSONObject.parseObject(variablesResponse, Map.class);
//                    log.info("基于变量中心采集的数据，更新上下文。type={}", type);
                    PipelineContextHolder.putInContext(nodeCode, fieldInfo);
                    return engineResultEnum;
                }
                if (String.valueOf(CreditInquiryStatus.QUERY_FAIL.getCode()).equals(code)) {
                    log.warn("征信查询终止...");
                    meterRegistry.counter("xengine_xdata_credit_end_total").increment();
                    decisionResultService.updateDecisionResultCodeById(bizId, null, EngineResultEnum.CREDIT_PENDING_END.getCode());
                    return engineResultEnum.setEngineResultEnum(EngineResultEnum.CREDIT_PENDING_END);
                }
            } else {
                //基本不会进入
                meterRegistry.counter("xengine_xdata_" + type + "_null_total", PrometheusTagsConstants.XDATA_API_TOTAL_TAGS.and("code", code)).increment();
            }
            log.error("getNodeFieldValue from data-server failed. ");
            if (CollectTypeEnum.PRE == type) {
                //预采集接口的响应，不影响后续处理
            } else if (CollectTypeEnum.REAL == type) {
                engineResultEnum.setEngineResultEnum(EngineResultEnum.DATASOURCE_FAIL);
            } else if (CollectTypeEnum.CREDIT == type) {
                engineResultEnum.setEngineResultEnum(EngineResultEnum.DATASOURCE_FAIL);
            }else{
                engineResultEnum.setEngineResultEnum(EngineResultEnum.DATASOURCE_FAIL);
            }
        } catch (Exception e) {
            Long end = System.currentTimeMillis();
            Cat.logError(e);
            transaction.setStatus(e);
            log.error("getNodeFieldValue from data-server exception. error={},respond={},variableApiRequest={}", e.getMessage(), end - start, JsonUtil.toJson(variableApiRequest), e);
            if (CollectTypeEnum.PRE == type) {
                //预采集接口异常，不阻塞整体流程
                engineResultEnum.setEngineResultEnum(EngineResultEnum.PROCESSING);
            } else {
                engineResultEnum.setEngineResultEnum(EngineResultEnum.DATASOURCE_EXCEPTION);
            }
            XDecisionContext.getContext().getStateContext().setEngineResultEnum(engineResultEnum.getEngineResultEnum());
            code = "ex";
        } finally {
            transaction.complete();
            sendQueryLog(fields, respond, response, code);
        }
        return engineResultEnum;
    }

    */
/**
     * 人行变量申请接口
     * private String idCardNumber;
     * private String idCardProtyle;
     * private String mobile;
     * private String creditChannel;
     * private String orderNumber;
     * private String type;
     * private String innerApp;
     * private String appId;
     * private String app;
     * private String name;
     * private String stage;
     *
     * @param nodeCode
     * @param fields
     *//*

    public boolean creditCollect(String nodeCode, Set<String> fields) {
        if (PipelineContextHolder.isInvokeRemote() == false) {
            log.info("测试数据不发起远程调用");
            return true;
        }
        String code = "null";
        boolean result = false;
        String response = "";
        long respond = 0;
        Transaction transaction = Cat.newTransaction("xengine", CollectTypeEnum.CREDIT_DATA.name());
        try {
            if (CollectionUtils.isEmpty(fields)) {
                log.info("取消获取人行变量数据请求，fields set is empty.");
                meterRegistry.counter("xengine_xdata_credit_null_total", PrometheusTagsConstants.XDATA_API_TOTAL_TAGS).increment();
                return true;
            }
            ConcurrentMap<String, Object> contextValue = PipelineContextHolder.getContextValue();
            String decisionId = PipelineContextHolder.getDecisionId();
            CreditVarRequest request = new CreditVarRequest();
            request.setRequestId(decisionId);
            request.setVarCodes(fields);
            request.setInputParams(JSONObject.parseObject(JsonUtils.toJsonString(contextValue)));

            Long start = System.currentTimeMillis();
            CreditVarResponse dataApiResponse = riskDataApiInterface.creditCollect(request);

            Long end = System.currentTimeMillis();
            respond = end - start;

            Metrics.gauge("xengine_xdata_credit_respond", PrometheusTagsConstants.XDATA_API_RESPOND_TAGS.and(Tags.of("type", "credit_apply")), respond);
            transaction.setDurationInMillis(respond);
            transaction.setStatus(Transaction.SUCCESS);

            if (null != dataApiResponse) {
                code = dataApiResponse.getCode();
                if (String.valueOf(XDecisionDataExceptionType.SUCCESS.code).equals(code)) {
                    log.info("人行变量申请接口成功，response={}", JsonUtils.toJsonString(dataApiResponse));
                    result = true;
                }
            }
            response = JsonUtils.toJsonString(dataApiResponse);

            log.info("人行变量申请，request={},response={}", JsonUtils.toJsonString(request), JsonUtils.toJsonString(dataApiResponse));
        } catch (Exception e) {
            Cat.logError(e);
            log.error("人行变量申请失败 from data server failed. error={}", e.getMessage(), e);
            result = false;
            transaction.setStatus(e);
            code = "ex";
        } finally {
            transaction.complete();
            sendQueryLog(fields, respond, response, code);
        }
        meterRegistry.counter("xengine_xdata_credit_total", PrometheusTagsConstants.XDATA_API_TOTAL_TAGS.and("code", code)).increment();
        return result;
    }


    private void sendQueryLog(Set<String> varCodes, long respond, String response, String code) {
        DecisionDataQueryLog decisionDataQueryLog = new DecisionDataQueryLog();
        decisionDataQueryLog.setDecisionId(PipelineContextHolder.getDecisionId());
        decisionDataQueryLog.setRequestId(PipelineContextHolder.getRequestId());
        decisionDataQueryLog.setEngineCode(PipelineContextHolder.getEngineCode());
        decisionDataQueryLog.setEngineName(PipelineContextHolder.getEngineName());
        decisionDataQueryLog.setEngineVersion(PipelineContextHolder.getEngineVersion());
        decisionDataQueryLog.setType(CollectTypeEnum.CREDIT_DATA.name());
        decisionDataQueryLog.setVarCodes(varCodes);
        decisionDataQueryLog.setRespond(respond);
        decisionDataQueryLog.setCode(code);
        decisionDataQueryLog.setResponse(response);

        XDecisionMessage msg = new XDecisionMessage();
        try {
            String decisionId = PipelineContextHolder.getDecisionId();
            String bizId = PipelineContextHolder.getRequestId();

            String nodeLogs = JsonUtils.toJsonString(decisionDataQueryLog);
            msg.setData(nodeLogs);
            msg.setMsgId(bizId + "_" + decisionId);
            msg.setKey(PipelineContextHolder.getEngineCode());
            CompletableFuture<MessageId> completableFuture = xPulsarProducer.sendAsync(queryLogTopic, msg);
            Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
            completableFuture.thenAccept(msgId -> {
                MDC.setContextMap(copyOfContextMap);
                log.info("query xdata log message send success。msgId={},decisionId={}，bizId={}", msgId.toString(), decisionId, bizId);
            }).exceptionally(ex -> {
                MDC.setContextMap(copyOfContextMap);
                log.error("query xdata log message send fail。decisionId={}，bizId={}", decisionId, bizId, ex);
                return null;
            });

        } catch (Exception exception) {
            log.error("send query xdata  log fail .nodeLogTopic={},msg={}", queryLogTopic, JsonUtils.toJsonString(msg), exception);
        }
    }
}
*/
